from flask import abort
from utilities import mysql_helper
from config import mysql_database
from flask_login import current_user
from functools import wraps

all_cn = {}

sql = 'select * from protal_role'
result = mysql_helper.getresult(sql, (), mysql_database['portal'])
for row in result:
    all_cn[row[1]] = (row[2], row[3])


def get_all_cn():
    global all_cn
    role_all_cn = {}
    for key in all_cn.keys():
        role_all_cn[key] = all_cn[key][0].split(',')
    return role_all_cn


def get_all_cn_details():
    global all_cn
    role_all_cn = {}
    for key in all_cn.keys():
        role_all_cn[key] = (all_cn[key][0].split(','), all_cn[key][1])
    return role_all_cn


def check_role(scope):
    def _deco1(func):
        @wraps(func)
        def __deco1():
            if scope in get_all_cn()[current_user.get_cn()] or 'all' in get_all_cn()[current_user.get_cn()]:
                return func()
            else:
                abort(401)

        return __deco1

    return _deco1


def update_cn_scope(scope, cn):
    global all_cn
    sql_update = 'update protal_role set scope="%s" where role="%s"' % (scope, cn)
    try:
        mysql_helper.executesql(sql_update, (), mysql_database['portal'])
        all_cn[cn] = (scope, all_cn[cn][1])
        return '1'
    except Exception, e:
        return '0'
